<template>
  <view class="register-container">
    <view class="logo-section">
      <view class="logo"></view>
      <view class="title">账号注册</view>
    </view>
    
    <view class="form-section">
		
		<form @submit="register">
			<view class="input-group">
				<view class="input-icon">
				  <text class="iconfont icon-user"></text>
				</view>
				<input type="text" v-model="username" placeholder="请设置用户名" placeholder-class="placeholder-style" />
			</view>
			
			<view class="input-group">
			  <view class="input-icon">
				<text class="iconfont icon-account"></text>
			  </view>
			  <input type="number" v-model="account" placeholder="请输入账号" placeholder-class="placeholder-style" />
			</view>
			<view class="input-group">
			  <view class="input-icon">
				<text class="iconfont icon-account_type"></text>
			  </view>
				<radio-group name="radio" v-bind:value="account_type" @change="onTypeChange">
					<label>
						<radio value="phone" /><text>手机号</text>
					</label>
					<label>
						<radio value="email" /><text>邮箱</text>
					</label>
				</radio-group>
			  
			</view>
			
			<view class="input-group">
			  <view class="input-icon">
				<text class="iconfont icon-password"></text>
			  </view>
			  <input type="password" v-model="password" placeholder="请设置密码" placeholder-class="placeholder-style" />
			</view>
			
			<view class="input-group">
			  <view class="input-icon">
				<text class="iconfont icon-password"></text>
			  </view>
			  <input type="password" v-model="confirmPassword" placeholder="请确认密码" placeholder-class="placeholder-style" />
			</view>
			<button class="register-btn" form-type="submit" :disabled="loading">
			  <text v-if="loading">注册中...</text>
			  <text v-else>注册</text>
			</button>
		</form>
      
      <view class="login-link">
        <text>已有账号？</text>
        <text class="link" @click="goToLogin">立即登录</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      username: '',
      account: '',
	    account_type:'',
      password: '',
      confirmPassword: '',
      loading: false
    };
  },

  methods: {
	  onTypeChange(e) {
	    // e.detail.value 即为当前选中的 radio 的 value（'phone' 或 'email'）
	    this.account_type = e.detail.value;
	    // 可选：打印日志验证是否更新成功
	    console.log('当前选中类型：', this.account_type);
	  },
    register: async function() {
		console.log(this.username,this.account,this.account_type,this.password);
      // 表单验证
      if (!this.username) {
        uni.showToast({
          title: '请设置用户名',
          icon: 'none'
        });
        return;
      }
      
      if(!this.account_type.value.trim()){
        errors.account='账号不能为空';
        return false;
       }
      if (this.account_type === 'phone') {
        // 验证手机号格式
        const phoneRegex = /^1[3-9]\d{9}$/;
        if (!phoneRegex.test(this.account)) {
          errors.account = '手机号格式不正确，请输入有效的手机号码';
          return false;
        }
      } else if (this.account_type === 'email') {
        // 验证邮箱格式
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(this.account)) {
          errors.account = '邮箱格式不正确，请输入有效的邮箱地址';
          return false;
        }
      }
      
      if (!this.password || this.password.length < 6) {
        uni.showToast({
          title: '密码至少6位',
          icon: 'none'
        });
        return;
      }
      
      if (this.password !== this.confirmPassword) {
        uni.showToast({
          title: '两次输入的密码不一致',
          icon: 'none'
        });
        return;
      }
      
      this.loading = true;
      
      try {
        // 构建注册数据
        const registerData = {
          username: this.username,
          account: this.account,
		      account_type:this.account_type,
          password: this.password
        };
        
        console.log('注册请求:', registerData);
        
        // 使用uni.request进行网络请求
        const [err, res] = await new Promise((resolve) => {
          // 检查是否是模拟环境
          const isMock = true; // 在实际环境中可以根据配置设置
          
          if (isMock) {
            // 模拟环境下直接使用setTimeout模拟请求延迟
            setTimeout(() => {
              // 模拟注册成功响应
              const mockResponse = {
                data: {
                  code: 200,
                  message: '注册成功',
                  data: {
                    userId: 'user_' + Date.now(),
                    username: this.username
                  }
                }
              };
              resolve([null, mockResponse]);
            }, 1500);
          } else {
            // 实际环境使用真实网络请求
            uni.request({
              url: 'http://localhost:8080/api/user/register',
              method: 'POST',
              data: registerData,
              success: (response) => resolve([null, response]),
              fail: (error) => resolve([error, null])
            });
          }
        });
        
        uni.showToast({
          title: '注册成功',
          icon: 'success'
        });
        
        // 注册成功后跳转到登录页
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/auth/login'
          });
        }, 1500);
        
      } catch (error) {
        console.error('注册失败:', error);
        uni.showToast({
          title: error.message || '注册失败，请重试',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    
    goToLogin: function() {
      uni.navigateTo({
        url: '/pages/auth/login'
      });
    }
  }
};
</script>

<style scoped>
.register-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60rpx 40rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
  box-sizing: border-box;
}

.logo-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 60rpx;
}

.logo {
  width: 180rpx;
  height: 180rpx;
  background-color: #FF6B6B;
  border-radius: 50%;
  margin-bottom: 30rpx;
}

.title {
  font-size: 40rpx;
  font-weight: bold;
  color: #333;
}

.form-section {
  width: 100%;
  max-width: 600rpx;
}

.input-group {
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 8rpx;
  padding: 0 30rpx;
  margin-bottom: 30rpx;
  height: 100rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.input-icon {
  margin-right: 20rpx;
  color: #999;
  font-size: 36rpx;
}

input {
  flex: 1;
  height: 100%;
  font-size: 32rpx;
  color: #333;
}

.placeholder-style {
  color: #ccc;
}

.register-btn {
  width: 100%;
  height: 100rpx;
  background-color: #FF6B6B;
  color: #fff;
  font-size: 36rpx;
  font-weight: bold;
  border-radius: 50rpx;
  margin-bottom: 30rpx;
}

.register-btn:active {
  opacity: 0.8;
}

.register-btn:disabled {
  background-color: #ccc;
  color: #fff;
}

.login-link {
  display: flex;
  justify-content: center;
  font-size: 28rpx;
  color: #666;
}

.link {
  color: #FF6B6B;
  margin-left: 10rpx;
}
</style>